﻿using System;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Reactor.Entities;
using Reactor.Messages.Commands.Core;
using Reactor.MiniManager.Events;
using Reactor.MiniManager.Views;
using Reactor.ServiceGrid.Extensions;

namespace Reactor.MiniManager.ViewModels
{
    public class ReactorCoreViewModel : ServiceViewModelBase<ReactorCoreEntity>
    {
        #region Fields
        
        private readonly IEventAggregator _eventAggregator;
        private ICommand _adoptCommand;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="ReactorCoreViewModel"/> class.
        /// </summary>
        /// <param name="reactorCore">The reactor core.</param>
        /// <param name="eventAggregator">The event aggregator.</param>
        public ReactorCoreViewModel(ReactorCoreEntity reactorCore, IEventAggregator eventAggregator) : base(reactorCore)
        {
            if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");

            _eventAggregator = eventAggregator;
            SubscriptionsImageControl = new SubscriptionsViewModel();

            _eventAggregator.GetEvent<ServicePackageDesignatedForAdoption>().Subscribe(IssueAdoptCommand);
        }

        public string StatusText
        {
            get { return (ServiceEntity.IsOnline) ? "online" : "offline"; }
        }

        public SubscriptionsViewModel SubscriptionsImageControl { get; set; }

        public ICommand AdoptCommand
        {
            get { return _adoptCommand ?? (_adoptCommand = new DelegateCommand(PromptForAdoptionDetails)); }
        }

        private static void PromptForAdoptionDetails()
        {
            var dialog = new AdoptServiceDetailsDialog();
            dialog.ShowDialog();
            dialog.Close();
        }

        private void IssueAdoptCommand(ServicePackageDesignatedForAdoption evnt)
        {
            var adoptCommand = new AdoptService();
            adoptCommand.IssueCommand(evnt.SelectedPackage.Id, evnt.SelectedPackage.Version, ServiceEntity.Identifier.Name, evnt.StartupArguments);
        }
    }
}
